import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
 
export const initThreeScene = (container) => {
  const scene = new THREE.Scene()
  scene.background  = new THREE.Color(0xf0f0f0)
  
  // 光照设置
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.8)
  scene.add(ambientLight) 
  
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.9)
  directionalLight.position.set(10,  10, -5)
  directionalLight.castShadow  = true 
  directionalLight.shadow.mapSize.width  = 2048 
  directionalLight.shadow.mapSize.height  = 2048
  scene.add(directionalLight) 
  
  // 相机设置
  const camera = new THREE.PerspectiveCamera(
    55,
    container.clientWidth  / container.clientHeight, 
    0.1,
    1000
  )
  camera.position.set(1,  1, 1)
  camera.lookAt(2, 0, 0)
  
  // 渲染器 
  const renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(container.clientWidth,  container.clientHeight) 
  renderer.shadowMap.enabled  = true 
  renderer.shadowMap.type  = THREE.PCFSoftShadowMap
  container.appendChild(renderer.domElement) 
  
  // 控制器
  const controls = new OrbitControls(camera, renderer.domElement) 
  controls.enableDamping  = true 
  controls.dampingFactor  = 0.05
  
  // 托盘组
  const palletGroup = new THREE.Group()
  scene.add(palletGroup) 
  
  // 动画循环
  const animate = () => {
    requestAnimationFrame(animate)
    controls.update() 
    renderer.render(scene,  camera)
  }
  animate()
  
  // 窗口大小调整
  const handleResize = () => {
    camera.aspect  = container.clientWidth  / container.clientHeight 
    camera.updateProjectionMatrix() 
    renderer.setSize(container.clientWidth,  container.clientHeight) 
  }
  window.addEventListener('resize',  handleResize)
  
  // 添加场景方法 
  scene.clearPallet  = () => {
    while (palletGroup.children.length  > 0) {
      palletGroup.remove(palletGroup.children[0]) 
    }
  }
  
  scene.getPalletGroup  = () => palletGroup 
  scene.handleResize  = handleResize 
  scene.renderer  = renderer 
  
  return scene 
}
 
export const disposeScene = (scene) => {
  if (!scene) return
  
  window.removeEventListener('resize',  scene.handleResize) 
  if (scene.renderer)  {
    scene.renderer.dispose() 
  }
}